from ise_api_0_login_info import username, password, url_prefix, headers
from ise_api_3_group import get_group_detail_by_id
import requests
from requests.auth import HTTPBasicAuth
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

getall_url = 'config/internaluser'


def get_all_user():
    r = requests.get(url_prefix + getall_url, auth=HTTPBasicAuth(username, password), headers=headers, verify=False)
    # print(r.json())
    user_list = []
    for x in r.json()['SearchResult']['resources']:
        user_list.append({'username': x.get('name'), 'id': x.get('id'), 'url': x.get('link').get('href')})

    return user_list


def get_user_detail(user_name):
    for user in get_all_user():
        if user.get('username') == user_name:
            # print(user.get('url'))
            r = requests.get(user.get('url'),
                             auth=HTTPBasicAuth(username, password),
                             headers=headers,
                             verify=False)
            user_data = r.json().get('InternalUser')
            if user_data.get('identityGroups', ''):
                return {'username': user_name,
                        'id': user_data.get('id'),
                        'enable': user_data.get('enabled'),
                        'url': user.get('url'),
                        'group': get_group_detail_by_id(user_data.get('identityGroups')).get('name')}
            else:
                return {'username': user_name,
                        'id': user_data.get('id'),
                        'enable': user_data.get('enabled'),
                        'url': user.get('url')}


if __name__ == "__main__":
    # print(get_all_user())
    print(get_user_detail('iseuser'))